<?php

// +----------------------------------------------------------------------
// | 文件 DeviceRemEvent.class.php
// +----------------------------------------------------------------------
// | 说明 设备推荐信息的缓存处理
// +----------------------------------------------------------------------
// | 
// +----------------------------------------------------------------------
// | Author: 谢赤心 Legend. <xcx_legender@qq.com>
// +----------------------------------------------------------------------

namespace Api\Event\Cache;
use Api\Event\CacheEvent;

class DeviceRemEvent implements ICacheEvent
{	

	const DB = 1;

	static public function set($type, &$lists)
	{
		$redis = CacheEvent::instance(self::DB);
		$key   = "IMBA.GLOBAL.DEVICEREM.{$type}";
		$redis->delete($key);
		foreach ($lists as $score => $value) {
			$value = trim($value);
			$redis->zadd($key, $score, $value);
		}
	}

	static public function get($type)
	{
		$redis = CacheEvent::instance(self::DB);
		$key   = "IMBA.GLOBAL.DEVICEREM.{$type}";
		return $redis->zrange($key, 0, -1, true);
	}


	static public function set_score($type, &$config)
	{
		$redis = CacheEvent::instance(self::DB);
		$lists = self::get($type);
		
		$configs = explode("\r\n", $config);
		$lastrate = -1;
		$rates = [];

		$rKey = "IMBA.GLOBAL.DEVICEREM.{$type}.RATE";
		$redis->delete($rKey);
		$res = [];
		foreach ($configs as $item) {
			$items = explode(':', $item);
			if (count($items) < 2){
				return false;
			}
			$key = trim($items[0]);
			$rate = intval($items[1]);
			if ($rate == 0){
				return false;
			}
			if (!array_key_exists($key, $lists)){
				return false;
			}
			if ($rate <= $lastrate || in_array($rate, $rates)){
				return false;
			}
			$rates[]  = $lastrate = $rate;

			$res[$lists[$key]] = $rate;
		}

		$redis->hmset($rKey, ['config' => $config, 'rate' => serialize($res)]);
		return true;
	}

	static public function get_score($type)
	{
		$redis = CacheEvent::instance(self::DB);
		$key   = "IMBA.GLOBAL.DEVICEREM.{$type}.RATE";
		$res = $redis->hgetall($key);
		if ($res){
			$res['rate'] = unserialize($res['rate']);
		}
		return $res;
	}

}